package com.jdyfy.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jdyfy.entity.Menu;
import com.jdyfy.entity.Role;
import com.jdyfy.entity.RoleMenu;
import com.jdyfy.mapper.RoleMapper;
import com.jdyfy.mapper.RoleMenuMapper;
import com.jdyfy.service.MenuService;
import com.jdyfy.service.RoleService;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements RoleService {

    @Autowired
    private RoleMapper roleMapper;

    @Resource
    private RoleMenuMapper roleMenuMapper;

    @Resource
    private MenuService menuService;

    // 删除角色
    @Override
    public int delById(Long id) {
        if (id == null) {
            return 0;
        }
        return roleMapper.delById(id);
    }

    // 绑定角色和菜单
    @Transactional
    @Override
    public void setRoleMenu(Long roleId, List<Long> menuIds) {
//        QueryWrapper<RoleMenu> queryWrapper = new QueryWrapper<>();
//        queryWrapper.eq("role_id", roleId);
//        roleMenuMapper.delete(queryWrapper);

        // 先删除当前角色对应的所有菜单
        roleMenuMapper.deleteRoleId(roleId);

        // 再把前端传过来的菜单id数组绑定到当前的这个角色id上
        List<Long> menuIdsCopy = CollUtil.newArrayList(menuIds);
        for (Long menuId : menuIds) {
            Menu menu = menuService.getById(menuId);
            if (menu.getPid() != null && !menuIdsCopy.contains(menu.getPid()) ) { // 二级菜单 并且 没有传父级id
                //补上父级id
                RoleMenu roleMenu = new RoleMenu();
                roleMenu.setRoleId(roleId);
                roleMenu.setMenuId(menu.getPid());
                roleMenuMapper.insert(roleMenu);
                menuIdsCopy.add(menu.getPid());
            }

            RoleMenu roleMenu = new RoleMenu(roleId, menuId);
            roleMenuMapper.insert(roleMenu);
        }
    }

    // 根据角色id查询所拥有的菜单id
    @Override
    public List<Long> getRoleMenu(Long roleId) {
        return roleMenuMapper.selectByRoleId(roleId);
    }
}
